All files / src/app/api/collections/[id]/pool/group route.ts

100% Statements 26/26
100% Branches 15/15
100% Functions 2/2
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                      13x 13x 13x 1x     12x   12x 12x     9x 9x   1x   8x 13x     59x   3x   5x 1x             4x   13x 13x 13x 1x 1x   3x 2x   1x      
import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { requireApiCapability } from "@/server/dal/collection-access";
import { ItemService, MAX_GROUP_PHOTOS } from "@/server/services/ItemService";
import { POOL_CAP_MESSAGE } from "@/lib/pool-limits";
import { errorResponse } from "@/server/api/http-errors";
 
// Groups selected pooled photos into one new (nameless, catalog-numbered) item.
// photos:write = curator (full-curator model).
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await getSession();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
 
  const db = getDb();
  // photos:write = curator — any curator may group pool photos (full-curator model).
  const access = await requireApiCapability(db, id, session.user.id, "photos:write");
  if (access instanceof NextResponse) return access;
 
  let body: unknown;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid body" }, { status: 400 });
  }
  const photoIds = (body as { photoIds?: unknown })?.photoIds;
  if (
    !Array.isArray(photoIds) ||
    photoIds.length === 0 ||
    !photoIds.every((x) => typeof x === "string")
  ) {
    return NextResponse.json({ error: "photoIds must be a non-empty string array" }, { status: 400 });
  }
  if (photoIds.length > MAX_GROUP_PHOTOS) {
    return NextResponse.json(
      { error: POOL_CAP_MESSAGE },
      { status: 400 },
    );
  }
 
  // mode is lenient: "each" makes one item per photo; anything else falls back to "combine".
  const mode = (body as { mode?: unknown })?.mode === "each" ? "each" : "combine";
 
  const service = ItemService.fromDb(db);
  try {
    if (mode === "each") {
      const items = await service.createItemsFromPoolEach(id, photoIds as string[]);
      return NextResponse.json({ count: items.length }, { status: 201 });
    }
    const item = await service.createItemFromPool(id, photoIds as string[]);
    return NextResponse.json({ number: item.number }, { status: 201 });
  } catch (error) {
    return errorResponse(error);
  }
}